import { defineStore } from 'pinia';

// 交易类型定义
export interface Transaction {
  id: string;
  date: string;
  type: 'income' | 'expense';
  category: string;
  amount: number;
  description?: string;
}

// 分类定义
export interface Category {
  id: string;
  name: string;
  type: 'income' | 'expense';
}

export const useFinanceStore = defineStore('finance', {
  state: () => ({
    transactions: [] as Transaction[],
    categories: [
      { id: '1', name: '工资', type: 'income' },
      { id: '2', name: '奖金', type: 'income' },
      { id: '3', name: '投资收益', type: 'income' },
      { id: '4', name: '餐饮', type: 'expense' },
      { id: '5', name: '交通', type: 'expense' },
      { id: '6', name: '购物', type: 'expense' },
      { id: '7', name: '住房', type: 'expense' },
      { id: '8', name: '医疗', type: 'expense' },
      { id: '9', name: '教育', type: 'expense' },
      { id: '10', name: '娱乐', type: 'expense' }
    ] as Category[],
    balance: 0
  }),
  
  getters: {
    // 获取收入分类
    incomeCategories: (state) => state.categories.filter(cat => cat.type === 'income'),
    
    // 获取支出分类
    expenseCategories: (state) => state.categories.filter(cat => cat.type === 'expense'),
    
    // 计算总收入
    totalIncome: (state) => state.transactions
      .filter(t => t.type === 'income')
      .reduce((sum, t) => sum + t.amount, 0),
    
    // 计算总支出
    totalExpense: (state) => state.transactions
      .filter(t => t.type === 'expense')
      .reduce((sum, t) => sum + t.amount, 0),
    
    // 计算余额
    currentBalance: (state) => state.balance,
    
    // 按日期排序的交易记录
    sortedTransactions: (state) => [...state.transactions].sort((a, b) => 
      new Date(b.date).getTime() - new Date(a.date).getTime()
    ),
    
    // 获取月度统计数据
    monthlyStats: (state) => {
      const stats: Record<string, { income: number; expense: number }> = {};
      
      state.transactions.forEach(t => {
        const date = new Date(t.date);
        const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
        
        if (!stats[monthKey]) {
          stats[monthKey] = { income: 0, expense: 0 };
        }
        
        if (t.type === 'income') {
          stats[monthKey].income += t.amount;
        } else {
          stats[monthKey].expense += t.amount;
        }
      });
      
      return stats;
    },
    
    // 获取分类统计数据
    categoryStats: (state) => {
      const stats: Record<string, number> = {};
      
      state.transactions.forEach(t => {
        if (!stats[t.category]) {
          stats[t.category] = 0;
        }
        stats[t.category] += t.amount;
      });
      
      return stats;
    }
  },
  
  actions: {
    // 添加交易记录
    addTransaction(transaction: Omit<Transaction, 'id'>) {
      const newTransaction = {
        ...transaction,
        id: Date.now().toString()
      };
      
      this.transactions.push(newTransaction);
      
      // 更新余额
      if (newTransaction.type === 'income') {
        this.balance += newTransaction.amount;
      } else {
        this.balance -= newTransaction.amount;
      }
      
      this.saveToLocalStorage();
    },
    
    // 删除交易记录
    deleteTransaction(id: string) {
      const index = this.transactions.findIndex(t => t.id === id);
      if (index !== -1) {
        const transaction = this.transactions[index];
        
        // 更新余额
        if (transaction.type === 'income') {
          this.balance -= transaction.amount;
        } else {
          this.balance += transaction.amount;
        }
        
        this.transactions.splice(index, 1);
        this.saveToLocalStorage();
      }
    },
    
    // 更新交易记录
    updateTransaction(id: string, updates: Partial<Transaction>) {
      const index = this.transactions.findIndex(t => t.id === id);
      if (index !== -1) {
        const oldTransaction = this.transactions[index];
        
        // 如果金额或类型改变，先调整余额
        if (updates.amount !== undefined && updates.amount !== oldTransaction.amount) {
          if (oldTransaction.type === 'income') {
            this.balance -= oldTransaction.amount;
          } else {
            this.balance += oldTransaction.amount;
          }
        }
        
        if (updates.type !== undefined && updates.type !== oldTransaction.type) {
          // 类型改变，先减去原类型的金额
          if (oldTransaction.type === 'income') {
            this.balance -= oldTransaction.amount;
          } else {
            this.balance += oldTransaction.amount;
          }
        }
        
        // 更新交易记录
        this.transactions[index] = { ...oldTransaction, ...updates };
        const newTransaction = this.transactions[index];
        
        // 加上新类型和金额
        if (newTransaction.type === 'income') {
          this.balance += newTransaction.amount;
        } else {
          this.balance -= newTransaction.amount;
        }
        
        this.saveToLocalStorage();
      }
    },
    
    // 添加分类
    addCategory(category: Omit<Category, 'id'>) {
      const newCategory = {
        ...category,
        id: Date.now().toString()
      };
      
      this.categories.push(newCategory);
      this.saveToLocalStorage();
    },
    
    // 从本地存储加载数据
    loadFromLocalStorage() {
      const data = localStorage.getItem('financeData');
      if (data) {
        const parsedData = JSON.parse(data);
        this.transactions = parsedData.transactions || [];
        this.categories = parsedData.categories || this.categories;
        this.balance = parsedData.balance || 0;
      } else {
        // 当没有数据时，初始化模拟数据
        this.initMockData();
      }
    },
    
    // 保存数据到本地存储
    saveToLocalStorage() {
      const data = {
        transactions: this.transactions,
        categories: this.categories,
        balance: this.balance
      };
      
      localStorage.setItem('financeData', JSON.stringify(data));
    },
    
    // 初始化一些模拟数据
    initMockData() {
      if (this.transactions.length === 0) {
        // 预设分类
        const defaultCategories = [
          { id: '1', name: '工资', type: 'income' },
          { id: '2', name: '奖金', type: 'income' },
          { id: '3', name: '兼职', type: 'income' },
          { id: '4', name: '投资收益', type: 'income' },
          { id: '5', name: '餐饮', type: 'expense' },
          { id: '6', name: '交通', type: 'expense' },
          { id: '7', name: '购物', type: 'expense' },
          { id: '8', name: '娱乐', type: 'expense' },
          { id: '9', name: '房租', type: 'expense' },
          { id: '10', name: '水电费', type: 'expense' },
          { id: '11', name: '通讯费', type: 'expense' },
          { id: '12', name: '医疗', type: 'expense' },
          { id: '13', name: '教育', type: 'expense' },
          { id: '14', name: '其他', type: 'income' },
          { id: '15', name: '其他', type: 'expense' }
        ];

        // 添加分类（保留原有的分类结构）
        this.categories = defaultCategories;

        // 生成最近30天的模拟交易数据
        const today = new Date();
        const mockTransactions: Transaction[] = [];
        
        // 模拟收入
        const incomeAmounts = [8000, 1500, 2000, 500, 1000];
        const incomeCategoryNames = ['工资', '奖金', '兼职', '投资收益', '其他'];
        
        // 模拟支出
        const expenseCategoryNames = ['餐饮', '交通', '购物', '娱乐', '房租', '水电费', '通讯费', '医疗', '教育', '其他'];
        const expenseAmounts = [30, 50, 200, 150, 3000, 300, 100, 500, 200, 100];
        const expenseNames = ['早餐', '午餐', '晚餐', '打车', '购物', '电影票', '房租', '水电费', '手机费', '医疗费', '培训费', '其他'];
        
        // 生成30天的交易数据
        for (let i = 29; i >= 0; i--) {
          const date = new Date(today);
          date.setDate(today.getDate() - i);
          
          // 每天1-3笔支出
          const expenseCount = Math.floor(Math.random() * 3) + 1;
          for (let j = 0; j < expenseCount; j++) {
            const categoryIndex = Math.floor(Math.random() * expenseCategoryNames.length);
            const amountIndex = Math.floor(Math.random() * expenseAmounts.length);
            const nameIndex = Math.floor(Math.random() * expenseNames.length);
            
            mockTransactions.push({
              id: `e-${Date.now()}-${i}-${j}`,
              amount: expenseAmounts[amountIndex],
              type: 'expense',
              category: expenseCategoryNames[categoryIndex],
              description: expenseNames[nameIndex],
              date: date.toISOString().split('T')[0]
            });
          }
          
          // 每隔几天添加一笔收入
          if (i % 7 === 0) {
            const categoryIndex = Math.floor(Math.random() * incomeCategoryNames.length);
            const amountIndex = Math.floor(Math.random() * incomeAmounts.length);
            
            mockTransactions.push({
              id: `i-${Date.now()}-${i}`,
              amount: incomeAmounts[amountIndex],
              type: 'income',
              category: incomeCategoryNames[categoryIndex],
              description: '收入',
              date: date.toISOString().split('T')[0]
            });
          }
          
          // 月底添加工资收入
          if (i === 29) {
            mockTransactions.push({
              id: `salary-${Date.now()}`,
              amount: 15000,
              type: 'income',
              category: '工资',
              description: '月薪',
              date: date.toISOString().split('T')[0]
            });
          }
        }

        this.transactions = mockTransactions;
        // 计算初始余额
        this.balance = mockTransactions
          .reduce((sum, t) => sum + (t.type === 'income' ? t.amount : -t.amount), 0);
        
        this.saveToLocalStorage();
      }
    }
  }
});